#include "KPF_StreamServiceSession.h"

#include "log.h"

KPF_StreamServiceSession::KPF_StreamServiceSession( const int8_t *pIP, const int16u_t iPort )
{
	CSessionParam stSessionParam;
		
	memset( &stSessionParam, 0x00, sizeof(stSessionParam) );
	memcpy( stSessionParam.pIP, (char *)pIP, strlen( (char *) pIP) + 1 );
	stSessionParam.iPort = iPort;
	
	log_print( (int8_t *)"start to create session............" );
	pm_Session = create_session( SESSION_TYPE_STREAM_SERVER, &stSessionParam );
	if ( pm_Session )
	{
		log_print( (int8_t *)"create tcp session ok................" );
		if ( set_session_business( pm_Session, onSessionBusiness, this ) >= 0 )
		{
			if ( set_session_event( pm_Session, onSessionEvent ) >= 0 )
			{
				log_print( (int8_t *)"stream server is running..............." );
			}
		}
	}
	else 
		log_print( (int8_t *)"create tcp server session failed????????????????????????" );
}
	
KPF_StreamServiceSession::~KPF_StreamServiceSession( void )
{
	
}
	
int32_t KPF_StreamServiceSession::handle_input( const KPF_Socket *pSocket, const int8u_t *pData, const int32_t iDataLen )
{
	int32_t iRetCode = -1;
	
	if ( pSocket && pData && iDataLen > 0 )
	{
		fwrite( pData, 1, iDataLen, stdout );
		fflush( stdout );		
		
		iRetCode = ((KPF_Socket *)pSocket)->Send( pData, iDataLen );	
	}
	
	return iRetCode;
}

int32_t KPF_StreamServiceSession::handle_output( const KPF_Socket *pSocket, const int8u_t *pData, const int32_t iDataLen )
{
	int32_t iRetCode = -1;
	
	if ( pSocket )
	{
		iRetCode = ((KPF_Socket *)pSocket)->Send( pData, iDataLen );	
	}
	
	return iRetCode;
}

int32_t KPF_StreamServiceSession::handle_event( const KPF_Event &eEvent )
{
	int32_t iRetCode = -1;
	
	if ( EVENT_READ_ERROR == ((KPF_Event)eEvent).getEvent() )
	{
		iRetCode = remove_session_socket( pm_Session, ((KPF_Event)eEvent).getEventParam().pSocket );
	}
	else if ( EVENT_ACCEPT_NEW_STREAM_CLIENT_NOTIFY == ((KPF_Event)eEvent).getEvent() )
	{
		CEventParam *pEventParam = &((KPF_Event)eEvent).getEventParam(  );
		
		if ( net_set_socket( pEventParam->pSocket, SOCKET_OPTION_NONE_BLOCK, NULL, 0 ) >= 0 )
		{
			log_print( (int8_t *)"accept_task: start to add reactor socket................" );
			if ( add_session_socket( pm_Session, pEventParam->pSocket ) >= 0 )
			{
				log_print( (int8_t *)"client:%s:%d", pEventParam->stNetAddr.pIP, pEventParam->stNetAddr.iPort );
				
				iRetCode = net_send( pEventParam->pSocket, (int8u_t *)"welcome\r\n", 9 );
				if ( iRetCode > 0 )
					log_print( (int8_t *)"accept_task: have send %d bytes.", iRetCode );		
			}	
			else 
				log_print( (int8_t *)"accept_task: add reactor socket failed??????????????????????" );		
		}
		else 
			log_print( (int8_t *)"accept_task: set none blocking socket failed????????????????????????" );	
	}
		
	return iRetCode;	
}
